const { sqlite3 } = require('../../mysql')

// 获取网站横幅数据
const getBanner = async (ctx) => {
  console.log('ctx.query:', ctx.query);
  let formData = ctx.query
  let offset = (formData.page - 1) * formData.limit
  let keyword = formData.query
  let limitdata = {}
  let data = {}
  if (keyword) {
    // console.log('query:', keyword)
    limitdata = await sqlite3('banner').where('name', 'LIKE', '%' + keyword + '%')
      .select()
    data = await sqlite3('banner').where('name', 'LIKE', '%' + keyword + '%')
      .orderBy('id', 'desc').select().limit(formData.limit).offset(offset)
  } else {
    limitdata = await sqlite3('banner').select()
    data = await sqlite3('banner').orderBy('id', 'desc')
      .select().limit(formData.limit).offset(offset)
  }
  if (data) {
    ctx.body = {
      code: 200,
      item: data,
      total: limitdata.length
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 添加网站横幅数据
const addBanner = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('banner').insert(
    formData
  )
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 更新网站横幅数据
const updateBanner = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('banner')
    .where('id', formData.id)
    .update(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 删除网站横幅数据
const delBanner = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('banner')
    .where('id', formData.id).del()
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

module.exports = { getBanner, addBanner, updateBanner, delBanner }